package com.enjoy.rpc;

import com.enjoy.rpc.common.ServerUtils;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by HP on 2019/7/3.
 */
public class RegisCenter {
    private static final ConcurrentHashMap<String, List<String>> serviceHolder = new ConcurrentHashMap<String, List<String>>();
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(4);

    public static void main(String[] args) throws IOException {
        //注册中心启动
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress(10002));
        System.out.println("Start RegisCnter.......");
        try {
            while (true) {
                executorService.execute(new RegisOrQueryTask(serverSocket.accept()));
            }
        } finally {
            serverSocket.close();
        }

    }


    private static class RegisOrQueryTask implements Runnable {

        private Socket socket = null;

        public RegisOrQueryTask(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                ObjectInputStream inputStream =
                        new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream =
                        new ObjectOutputStream(socket.getOutputStream());

                //接收客户端的输出，也就是服务器的输入
                String flag = inputStream.readUTF();
                String info = inputStream.readUTF();
                //注册服务
                if ("R".equals(flag)) {
                    boolean isRedis = ServerUtils.register(serviceHolder, info);
                    if (isRedis) {
                        System.out.println(info + "服务注册成功！");
                        outputStream.writeUTF("注册成功");
                        outputStream.flush();
                    }
                } else if ("Q".equals(flag)) {//查询服务
                    String infoServer = ServerUtils.find(serviceHolder, info);
                    if (infoServer != null) {
                        outputStream.writeUTF(infoServer);
                        outputStream.flush();
                    } else {
                        System.out.println("未找到对应的服务" + info);
                        outputStream.writeUTF("F");
                        outputStream.flush();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
